package com.tsinghuabigdata.edu.ddmath.module.mylearn;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.ZxApplication;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.bean.WaitWorkBean;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.ToastUtils;

import java.io.File;

/**
 * 预览图片界面
 */
public class XBookPreviewActivity extends Activity implements View.OnClickListener {

    //
    private ImageView photoView;
    private Context mContext;

    private String imagePath;
    private Bitmap mBitmap;

    //传递过来的参数
    private String imageType;
    private boolean isNextImage;
    private boolean isBroadCast;
    //此次上传作业的ID，本地使用
    private String mTaskId;


    @Override
    protected void onCreate( Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        //设置全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView( R.layout.activity_xbook_preview );
        mContext = this;

        if( !parseIntent() ){
            ToastUtils.showShort( this, "参数错误" );
            finish();
            return;
        }
        initView();
    }

    @Override
    public void onClick(View v) {
        if( v.getId() == R.id.mylearn_finishbtn ){

            ToastUtils.showToastCenter( mContext, "已保存" );

            //先把图片加入作业列表
            addImageToWaitWork();

            //进入下一个页面
            if( isBroadCast ){
                sendAddImageBoardcast();
                sendCloseActivity();
                finish();
            }else{
                sendCloseActivity();
                finish();
                sendStartWaitUploadBoardcast();
            //    startActivity( new Intent(getBaseContext(), WaitUploadActivity.class) );
                //AppLog.d("fdsfdsfdsfd startt");
            }

            //保存数据列表
            LocalWorkManager localWorkManager = LocalWorkManager.getLocalWorkManager();
            if( localWorkManager != null ) localWorkManager.saveData();

        }else if(v.getId() == R.id.mylearn_nextbtn ){

            //先把图片加入作业列表
            addImageToWaitWork();

            //在判断目前已经拍照几页
            if( hasManyImage() ){
                ToastUtils.showToastCenter( getBaseContext(), getResources().getString(R.string.many_image) );
                return;
            }

            ToastUtils.showToastCenter( mContext, "已保存" );

            //先通知更新
            if( isBroadCast ){
                sendAddImageBoardcast();
            }

            sendCloseActivity();

            //拍摄下一题
            Intent intent = new Intent( getBaseContext(), XBookCameraActivity.class );
            intent.putExtra( XBookUtils.IS_NEXT_IMAGE, true );
            intent.putExtra( XBookUtils.TASK_ID, mTaskId );
            intent.putExtra( XBookUtils.PARAM_BROADCAST, isBroadCast );
            startActivity( intent );
            finish();

        }else if( v.getId() == R.id.mylearn_preview_redo ){

            //先删除当前图片
            File file = new File(imagePath);
            file.delete();

            //进入新的拍照界面
//            Intent intent = new Intent( getBaseContext(), XBookCameraActivity.class );
//            intent.putExtra( XBookUtils.IS_NEXT_IMAGE, isNextImage );
//            intent.putExtra( XBookUtils.TASK_ID, mTaskId );
//            intent.putExtra( XBookUtils.PARAM_BROADCAST, isBroadCast );
//            startActivity( intent );

            finish();
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        if( mBitmap != null ){
            mBitmap.recycle();
            mBitmap = null;
        }
    }
    //----------------------------------------------------------------------
    //解析参数,必须在initView之前调用
    private boolean parseIntent(){

        Intent intent = getIntent();

        if( !intent.hasExtra(XBookUtils.IMAGE_TYPE) || !intent.hasExtra(XBookUtils.IMAGE_HANDLE) )
            return false;

        isNextImage = intent.getBooleanExtra( XBookUtils.IS_NEXT_IMAGE, false );
        isBroadCast = intent.getBooleanExtra( XBookUtils.PARAM_BROADCAST, false );
        mTaskId     = intent.getStringExtra( XBookUtils.TASK_ID );
        imageType   = intent.getStringExtra( XBookUtils.IMAGE_TYPE );

        if( XBookUtils.TYPE_LOCAL.equals(imageType) ){             //本地图片路径
            imagePath = intent.getStringExtra( XBookUtils.IMAGE_HANDLE );
            AppLog.d("dfddfd imagePath = " + imagePath );
        }else if( XBookUtils.TYPE_BITMAP.equals( imageType ) ){    //bitmap对象
            int session = intent.getIntExtra(XBookUtils.IMAGE_HANDLE,-1);
            mBitmap = XBookUtils.getBitmap( session );
            XBookUtils.removeBitmap( session );
        }

        if( isNextImage ){      //是继续拍摄
            mTaskId = intent.getStringExtra( XBookUtils.TASK_ID );
        }
        return true;
    }

    private void initView(){

        photoView = (ImageView)findViewById( R.id.mylearn_preview_photo );

        //结束拍摄
        TextView finishBtn = (TextView)findViewById( R.id.mylearn_finishbtn );
        finishBtn.setOnClickListener( this );

        //再拍一张
        TextView nextBtn = (TextView)findViewById( R.id.mylearn_nextbtn );
        nextBtn.setOnClickListener( this );
        //重拍
        RelativeLayout redoBtn = (RelativeLayout) findViewById( R.id.mylearn_preview_redo );
        redoBtn.setOnClickListener( this );


        if( mBitmap != null ){
            photoView.setImageBitmap( mBitmap );
        }else if( !TextUtils.isEmpty(imagePath) ){             //本地图片路径
            mBitmap = BitmapFactory.decodeFile(imagePath);
            photoView.setImageBitmap( mBitmap );
        }

    }

    //
    private String createWaitWorkBean(){
        LocalWorkManager localWorkManager = initLocalWorkMananger();
        if( localWorkManager == null ) return "";

        WaitWorkBean workBean = localWorkManager.getNotUploadWaitWork();
        if( workBean == null ){
            workBean = new WaitWorkBean();
            localWorkManager.addWaitWorkTask( workBean );
        }
        return workBean.getTaskId();
    }

    //
    private boolean addImageToWaitWork(){

        if( TextUtils.isEmpty(mTaskId) ){ //是第一张拍摄,建立
            mTaskId = createWaitWorkBean();
        }

        LocalWorkManager localWorkManager = initLocalWorkMananger();
        if( localWorkManager == null ){
            return false;
        }
        WaitWorkBean workBean = localWorkManager.getWaitWorkTask( mTaskId );
        if( workBean == null ){
            ToastUtils.showShort( getBaseContext(), "LocalWorkManager workBean no find");
            return false;
        }
        //检查是否重复，保证不重复添加
        if( workBean.hasImagePath( imagePath) ) return true;
        //添加
        workBean.addUploadImage( imagePath );

        //如果超过最大页，删除添加的
        if( workBean.getImageList().size() > AppConst.MAX_WORK_IMAGE ){
            workBean.removeAddTypeImage();
        }
        return true;
    }

    private boolean hasManyImage(){

        LocalWorkManager localWorkManager = initLocalWorkMananger();
        if( localWorkManager == null ){
            return false;
        }
        WaitWorkBean workBean = localWorkManager.getWaitWorkTask( mTaskId );
        if( workBean == null ){
            ToastUtils.showShort( getBaseContext(), "LocalWorkManager workBean no find");
            return false;
        }
        return workBean.getImageCount() >= AppConst.MAX_WORK_IMAGE;
    }

    private void sendCloseActivity(){
        sendBroadcast( new Intent( AppConst.ACTION_CLOSE_ACTIVITY ) );
    }
    private void sendAddImageBoardcast(){
        Intent it = new Intent( AppConst.ACTION_XBOOK_ADD );
        sendBroadcast( it );
    }
    private void sendStartWaitUploadBoardcast(){
        Intent it = new Intent( AppConst.ACTION_START_WAITUPLOAD );
        ZxApplication.getApplication().sendBroadcast( it );
    }

    private LocalWorkManager initLocalWorkMananger(){

        LocalWorkManager localWorkManager = LocalWorkManager.getLocalWorkManager();
        if( localWorkManager != null ){
            return localWorkManager;
        }

        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if( loginInfo == null || TextUtils.isEmpty(loginInfo.getLoginName()) ){
            ToastUtils.showShort( getBaseContext(), "用户信息错误");
            return null;
        }
        return LocalWorkManager.getLocalWorkManager( mContext, loginInfo.getLoginName());
    }
}
